class_name DialogueUI
extends Control

# UI节点引用
@onready var dialogue_panel: Panel = $DialoguePanel
@onready var player_portrait: TextureRect = $DialoguePanel/HBoxContainer/PlayerPortrait
@onready var npc_portrait: TextureRect = $DialoguePanel/HBoxContainer/NPCPortrait
@onready var dialogue_text: RichTextLabel = $DialoguePanel/HBoxContainer/CenterContainer/VBoxContainer/DialogueText
@onready var speaker_label: Label = $DialoguePanel/HBoxContainer/CenterContainer/VBoxContainer/SpeakerLabel
@onready var continue_hint: Label = $DialoguePanel/HBoxContainer/CenterContainer/VBoxContainer/ContinueHint

# 默认角色图像
var default_player_portrait: Texture2D
var default_npc_portrait: Texture2D

func _ready():
	# 初始时隐藏对话面板
	hide_dialogue()
	
	# 加载默认角色图像
	load_default_portraits()

func load_default_portraits():
	"""加载默认角色图像"""
	# 加载默认玩家头像
	default_player_portrait = load("res://assets/player_portrait.svg")
	if default_player_portrait and player_portrait:
		player_portrait.texture = default_player_portrait
	
	# 加载默认NPC头像
	default_npc_portrait = load("res://assets/npc_portrait.svg")
	if default_npc_portrait and npc_portrait:
		npc_portrait.texture = default_npc_portrait

func show_dialogue():
	"""显示对话界面"""
	visible = true
	dialogue_panel.visible = true
	
	# 播放显示动画（可选）
	var tween = create_tween()
	dialogue_panel.modulate.a = 0.0
	tween.tween_property(dialogue_panel, "modulate:a", 1.0, 0.3)

func hide_dialogue():
	"""隐藏对话界面"""
	# 播放隐藏动画（可选）
	var tween = create_tween()
	tween.tween_property(dialogue_panel, "modulate:a", 0.0, 0.2)
	tween.tween_callback(func(): visible = false)

func update_dialogue(speaker: String, text: String, npc_portrait_texture: Texture2D = null, npc_name: String = ""):
	"""更新对话内容"""
	# 更新说话者标签
	if speaker == "player":
		speaker_label.text = "玩家"
		# 高亮玩家头像
		player_portrait.modulate = Color.WHITE
		npc_portrait.modulate = Color(0.7, 0.7, 0.7)
	elif speaker == "npc":
		speaker_label.text = npc_name if not npc_name.is_empty() else "NPC"
		# 高亮NPC头像
		player_portrait.modulate = Color(0.7, 0.7, 0.7)
		npc_portrait.modulate = Color.WHITE
	else:
		speaker_label.text = speaker
		# 重置头像高亮
		player_portrait.modulate = Color.WHITE
		npc_portrait.modulate = Color.WHITE
	
	# 更新对话文本
	dialogue_text.text = text
	
	# 更新NPC头像
	if npc_portrait_texture:
		npc_portrait.texture = npc_portrait_texture
	
	# 显示继续提示
	continue_hint.text = "按空格继续 (5秒后自动继续)"
	
	# 播放文字显示动画
	play_text_animation()

func play_text_animation():
	"""播放文字显示动画"""
	# 简单的淡入动画
	dialogue_text.modulate.a = 0.0
	var tween = create_tween()
	tween.tween_property(dialogue_text, "modulate:a", 1.0, 0.5)

func set_player_portrait(texture: Texture2D):
	"""设置玩家头像"""
	if player_portrait:
		player_portrait.texture = texture

func set_npc_portrait(texture: Texture2D):
	"""设置NPC头像"""
	if npc_portrait:
		npc_portrait.texture = texture
